package com.kmvc.message.activity;

import java.io.File;
import java.io.StringReader;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.database.Cursor;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.kmvc.message.R;
import com.kmvc.message.database.DbHelper;
import com.kmvc.message.entity.StringEntity;
import com.kmvc.message.handler.StringHandler;
import com.kmvc.message.tools.DownloadFile;
import com.kmvc.message.tools.WebService;

public class MessageApplication extends Application implements UncaughtExceptionHandler {
	public boolean isRefsh=false;
	public String keyString="";
	public String result="";
	private Context context;
	
	public String phonenum;
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    
    
    public HashMap<String,Boolean> DownLoadList=new HashMap<String, Boolean>();
	   
    int CansendMessage=0;
    Handler handler=new Handler();
    
    Runnable runnable=new Runnable() {
		@Override
		public void run() {
			CansendMessage--;
			if(CansendMessage!=0)
			{
				handler.postDelayed(runnable, 1000);
			}
			
		}
	};
	 
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		context=getApplicationContext();
		  // 获取系统默认的UncaughtException处理
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        // 设置重写的uncaughtException为程序的默认处理
        Thread.setDefaultUncaughtExceptionHandler(this);
        LoadImg();
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		 if(!handleException(ex) && mDefaultHandler!=null)
		 {
			 // 如果用户没有处理则让系统默认的异常处理器来处理
			 mDefaultHandler.uncaughtException(thread, ex);
		 }
		else {
			try {
				Thread.sleep(3000);
			} catch (Exception e) {
				 
			}
			 // 杀死线程，退出应用。
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
		}
	}

	  /**
     * @param 线程弹出自定义提示
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
	private boolean handleException(final Throwable ex) {
	 if (ex==null) {
		 return false;
	}
	 //使用Toast来显示异常信息
	 new Thread(){
		 public void run()
		 {
			 
			 if (!ex.toString().equals("java.lang.NullPointerException")) {
				 try 
				 {
					 ex.printStackTrace();
					 Log.e("kmvc",ex.getMessage());
					 WebService.ExceptionAdd(getString(R.string.app_name)+ex.toString(),android.os.Build.VERSION.RELEASE,android.os.Build.MODEL);
				} catch (Exception e) {
					 
				}
				
				 Looper.prepare();
				 Toast.makeText(context, "抱歉，程序异常错误，即将退出应用！",Toast.LENGTH_LONG).show();
				 Looper.loop();
			}
			
		 }
	 }.start();
		return true;
	}
	
	
	public void StartJishi()
	{
		
		handler.postDelayed(runnable, 1000);
	}
	
	List<StringEntity> mStringList;
	int flag=0;
	private Handler h = new Handler();
	Runnable r = new Runnable() {
		public void run() {
			if(mStringList!=null&&mStringList.size()>0)
			{
				DbHelper dbHelper=new DbHelper(context);
				if(flag==0)
				{
					dbHelper.insertImg(mStringList);
				}
				else 
				{
					dbHelper.insertSetting(mStringList);
				}
				dbHelper.close();
				
			}
			
			if(flag==0)
			{
				flag=1;
				DownLoadImg();
				LoadSetting();
			}
			
		}
	};
	
	
	
	protected void LoadImg()
	{
		 new Thread()
		 {
			 @Override
			 public void run()
			 {
				 DbHelper dbHelper=new DbHelper(context);
				 Cursor cursor=dbHelper.getLastDate(1);
				 String lastDate="2014-01-01 01:01:01";
				 if(cursor!=null&&cursor.getCount()>0)
				 {
					 if(cursor.moveToNext())
					 {
						 lastDate=cursor.getString(cursor.getColumnIndex("LastDate")); 
						 cursor.close();
					 }
				 }
				 dbHelper.close();
				 String message="<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>"
							+ WebService.getImgTable(lastDate);
					if (!message.equals("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>null")
							&& !message.equals("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><data></data>")) 
					{
						StringReader read = new StringReader(
								message.toString());
						InputSource mInputSource = new InputSource(read);
						try {
							SAXParserFactory msSaxParserFactory = SAXParserFactory
									.newInstance();
							SAXParser msSaxParser = msSaxParserFactory
									.newSAXParser();
							XMLReader msXmlReader = msSaxParser
									.getXMLReader();
							StringHandler mStringHandler = new StringHandler();
							msXmlReader.setContentHandler(mStringHandler);
							msXmlReader.parse(mInputSource);

							mStringList = mStringHandler.getParsedData();
						} catch (Exception e) 
						{
							e.toString();
						}
					}
					
					h.post(r);
				
			 }
			 
		 }.start();
	}
	
	
	protected void LoadSetting()
	{
		 new Thread()
		 {
			 public void run()
			 {
				 DbHelper dbHelper=new DbHelper(context);
				 Cursor cursor=dbHelper.getLastDate(2);
				 String lastDate="2014-01-01 01:01:01";
				 if(cursor!=null&&cursor.getCount()>0)
				 {
					 if(cursor.moveToNext())
					 {
						 lastDate=cursor.getString(0); 
						 cursor.close();
					 }
				 }
				 dbHelper.close();
				 String message="<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>"
							+ WebService.getAreaSetting(lastDate);
					if (!message.equals("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>null")
							&& !message.equals("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><data></data>")) 
					{
						StringReader read = new StringReader(
								message.toString());
						InputSource mInputSource = new InputSource(read);
						try {
							SAXParserFactory msSaxParserFactory = SAXParserFactory
									.newInstance();
							SAXParser msSaxParser = msSaxParserFactory
									.newSAXParser();
							XMLReader msXmlReader = msSaxParser
									.getXMLReader();
							StringHandler mStringHandler = new StringHandler();
							msXmlReader.setContentHandler(mStringHandler);
							msXmlReader.parse(mInputSource);

							mStringList = mStringHandler.getParsedData();
						} catch (Exception e) 
						{
							e.toString();
						}
					}
					
					h.post(r);
			 }
		 }.start();
	}
	
	protected void DownLoadImg()
	{
		new Thread()
		 {
			 public void run()
			 {
		
				 DbHelper dbHelper=new DbHelper(context);
				 Cursor cursor=dbHelper.getImgList();
			 	if(cursor!=null&&cursor.getCount()>0)
			 	{
			 		DownloadFile downloadFile=new DownloadFile();
			 		while (cursor.moveToNext()) 
			 		{
			 			String IMG_ID=cursor.getString(cursor.getColumnIndex("IMG_ID"));
			 			String IMG_URL=cursor.getString(cursor.getColumnIndex("IMG_URL"));
			 			String nameString="";
			 			String[] array=IMG_URL.split("/");
			 			if(array!=null&&array.length>1)
			 			{
			 				String SDPATH = Environment.getExternalStorageDirectory().getPath();
			 				nameString=array[array.length-1];
							String path=SDPATH+"/KMVC_MESSAGE/icon/"+nameString;
							File mfile=new File(path);
							if(!mfile.exists())
							{
								downloadFile.DownLoad(IMG_URL,nameString, context,nameString,"/KMVC_MESSAGE/icon/");
								Log.d("kmvc", "下载文件！");
							}
							dbHelper.UpdateImg(IMG_ID,nameString);
							
			 			}
					}
			 		
			 	}
 				dbHelper.close();
			 }
		 }.start();
	}
	
	
	public void LoadReportImg(String Content,String sendDate,String area,String url,DbHelper dbHelper)
	{
		String SDPATH = Environment.getExternalStorageDirectory().getPath();
		String[] array=url.split("/");
		String	nameString=array[array.length-1];
		String path=SDPATH+"/KMVC_MESSAGE/reportImg/"+nameString;
		File mfile=new File(path);
		if(!mfile.exists())
		{
			DownloadFile downloadFile=new DownloadFile();
			downloadFile.DownLoad(url,nameString, context,nameString,"/KMVC_MESSAGE/reportImg/");
		}
		dbHelper.UpdateReportImg(Content,sendDate,area,nameString);
	}
	
	
}
